/*
 * IBM Corporation.
 * Copyright (c) 2014 All Rights Reserved.
 */

package com.ibm.iisp.common.file.controller;

import java.io.IOException;
import java.net.URLEncoder;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.ibm.iisp.common.file.download.FileDownloader;

/**
 * 类作用：
 * @author Johnny@cn.ibm.com
 * 使用说明：
 */
@RequestMapping("/files")
public class FileDownloadController {
	private Logger log = LoggerFactory.getLogger(getClass());
	@Value("${file.download.root}")
	String fileDownloadRoot;

	@Inject
	FileDownloader fileDownloader;

	@RequestMapping(method = RequestMethod.GET)
	public void getFile(@RequestParam String path,HttpServletRequest request, HttpServletResponse resp) throws IOException {
		log.debug("下载文件文件{}", path);
//		String extName = path.substring(path.lastIndexOf(".") + 1, path.length()).toLowerCase();
//		// set content type
//		String contentType = null;
//		if (extName.equals("html") || extName.equals("htm")) {
//			contentType = "text/html";
//		} else if (extName.equals("png") || extName.equals("gif") || extName.equals("jpg")) {
//			contentType = "image/" + extName;
//		} else {
//			contentType = "application/" + extName;
//		}
		resp.setContentType("application/octet-stream");// 设置文件类型
		String fileName = path.substring(path.lastIndexOf("/") + 1);
		resp.addHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
		fileDownloader.download(path, request, resp);
	}
}
